﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.BackgroundTransfer;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Globalization;

namespace Cnblogs.Service
{
    /*
     * 理一下思路(Note:尚未实现)
     * 主要的功能是
     * 1、离线单个的文章、新闻
     * 2、循环离线某博主的20篇博客、或者指定条数的新闻
     *  离线的时候需要:
     *  2.1、离线时保存文本（即服务器返回的文本）
     *  2.2、离线时下载文章中图片（难点）
     * 3、支持后台下载
     * 
     * */
    public class OfflineService : INotifyPropertyChanged
    {
        #region Congig Constants
        private const string SharedTransfers = "\\shared\\transfers";
        private const int MaxPendingUploads = 5;
        private const int MaxFileSize = 20971520;
        private static readonly Dictionary<TransferStatus, string> Statuses = new Dictionary<TransferStatus, string>
        {                
            {TransferStatus.None, "Not Started" },
            {TransferStatus.Transferring, "Transferring" },
            {TransferStatus.Waiting, "Queued" },
            {TransferStatus.WaitingForWiFi, "Waiting for WiFi" },
            {TransferStatus.WaitingForExternalPower, "Waiting for power"},
            {TransferStatus.WaitingForExternalPowerDueToBatterySaverMode, "Waiting for power"},
            {TransferStatus.WaitingForNonVoiceBlockingNetwork, "Waiting for non voice blocking network"},
            {TransferStatus.Paused, "Paused"},
            {TransferStatus.Completed, "Completed"},
            {TransferStatus.Unknown, "Unknown"},
        };
        #endregion

        protected class BackgroundTransferServiceWrapper
        {
            public virtual IEnumerable<BackgroundTransferRequest> Requests
            {
                get
                {

                    return BackgroundTransferService.Requests;
                }
            }

            public virtual BackgroundTransferRequest Find(string requestId)
            {
                return BackgroundTransferService.Find(requestId);
            }

            public virtual void Add(BackgroundTransferRequest request)
            {
                BackgroundTransferService.Add(request);
            }

            public virtual void Remove(BackgroundTransferRequest request)
            {
                BackgroundTransferService.Remove(request);
            }
        }

        public class DownloadRequest
        {
            public string ImgPath { get; set; }
        }

        private static OfflineService _current;
        public static OfflineService Current
        {
            get
            {
                return OfflineService._current;
            }
        }

        private List<BackgroundTransferRequest> _pendingTransfers;
        protected OfflineService.BackgroundTransferServiceWrapper TransferService = new OfflineService.BackgroundTransferServiceWrapper();
        private int _totalRequestsCount;
        protected OfflineService()
        {
            using (IsolatedStorageFile userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!userStoreForApplication.DirectoryExists(SharedTransfers))
                {
                    userStoreForApplication.CreateDirectory(SharedTransfers);
                }
            }
        }

        static OfflineService()
        {
            _current = new OfflineService();
        }

        private void PopulatePendingList()
        {

        }

        private void CancelAllRequests()
        {
            this._pendingTransfers = Enumerable.ToList<BackgroundTransferRequest>(this.TransferService.Requests);
            using (IsolatedStorageFile userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (List<BackgroundTransferRequest>.Enumerator enumerator = this._pendingTransfers.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        BackgroundTransferRequest current = enumerator.Current;
                        current.TransferStatusChanged -= this.OnTransferStatusChanged;
                        this.TransferService.Remove(current);
                        string text = current.UploadLocation.ToString();
                        if (userStoreForApplication.FileExists(text))
                        {
                            userStoreForApplication.DeleteFile(text);
                        }
                    }
                }
            }
            this._pendingTransfers = Enumerable.ToList<BackgroundTransferRequest>(this.TransferService.Requests);

        }

        private void OnTransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {

        }

        #region 离线单个的文章
        /// <summary>
        /// 保存单个的文章
        /// </summary>
        /// <param name="id">文章id</param>
        /// <param name="post">文章内容</param>
        public void SaveSinglePost(string id, string post)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.DirectoryExists(id))
                {
                    store.CreateDirectory(id);
                }
                //string path=Path.Combine(id,)
                var it = HtmlUtility.SavedHtml(post, id);
            }
        }
        #endregion

        #region 离线文章中的图片
        public void SavePostImages()
        {

        }
        #endregion

        #region 离线指定条数的新闻
        public void SavePosts(ServiceType type, int count)
        {
            if (type == ServiceType.Home || type == ServiceType.Hot || type == ServiceType.Recent || type == ServiceType.Recommend)
            {
                FeedService.Request(type, new NewsData { PageIndex = 1, PageSize = count }, (obj, isSuccess) =>
                {
                    if (isSuccess)
                    {
                        
                    }
                });
            }
        }
        #endregion

        #region 离线博主的指定数目文章
        public void SaveBloggerPosts(string blogapp, int count)
        {
            FeedService.Request(ServiceType.Blogger, new NewsData { PageIndex = 1, PageSize = count }, (obj, isSuccess) =>
            {
                if (isSuccess)
                {

                }
            });
        }
        #endregion

        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

    }
}
